package com.gframework.mybatis.dao.mybatis.provider.core;

import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.Jdbc3KeyGenerator;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ResultSetType;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.scripting.LanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.springframework.util.StringUtils;

import com.gframework.mybatis.dao.mybatis.provider.PojoInfo;
import com.gframework.mybatis.dao.mybatis.provider.ProviderUtils;

/**
 * 扩展 MapperBuilderAssistant 类，针对keyColumn和keyProperty支持更多的获取方式。
 *
 * @since 1.0.0
 * @author Ghwolf
 */
public class ExtendMapperBuilderAssistant extends MapperBuilderAssistant {
	/**
	 * mapper 接口类型
	 */
	private Class<?> type ;
	
	public ExtendMapperBuilderAssistant(Configuration configuration, String resource,Class<?> type) {
		super(configuration, resource);
		this.type = type;
	}

	@Override
	public MappedStatement addMappedStatement(
		      String id,
		      SqlSource sqlSource,
		      StatementType statementType,
		      SqlCommandType sqlCommandType,
		      Integer fetchSize,
		      Integer timeout,
		      String parameterMap,
		      Class<?> parameterType,
		      String resultMap,
		      Class<?> resultType,
		      ResultSetType resultSetType,
		      boolean flushCache,
		      boolean useCache,
		      boolean resultOrdered,
		      KeyGenerator keyGenerator,
		      String keyProperty,
		      String keyColumn,
		      String databaseId,
		      LanguageDriver lang,
		      String resultSets) {
		
		// 如果没有直接指定keyColumn和keyProperty，而且keyGenerator=true，那么就通过POJO配置信息去读取
		if (keyGenerator == Jdbc3KeyGenerator.INSTANCE && (StringUtils.isEmpty(keyProperty) || StringUtils.isEmpty(keyColumn))) {
			PojoInfo pojo = ProviderUtils.getMybatisDaoInfo(this.type).getPojoInfo();
			keyProperty = pojo.getPkFieldName();
			keyColumn = pojo.getPkColumnName();
		}
		
		return super.addMappedStatement(id, sqlSource, statementType, sqlCommandType, fetchSize, timeout, parameterMap,
				parameterType, resultMap, resultType, resultSetType, flushCache, useCache, resultOrdered, keyGenerator,
				keyProperty, keyColumn, databaseId, lang, resultSets);
	}
	
}
